import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:kq_flutter_core_widget/utils/ex/kq_ex.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';
import 'package:kq_flutter_core_widget/widgets/image/kq_image.dart';

import '../../../theme/kq_theme_manager.dart';
import '../../config/kq_global.dart';
import '../../resources/images.dart';
import '../../resources/kq_theme_colors.dart';

class KqCheckSelectableGridView<T extends ICheckGridViewItemData>
    extends StatefulWidget {
  /// 是否多选
  final bool multiSelect;

  /// 未选中时的背景颜色
  final Color unselectedColor;

  ///选中时的背景颜色
  final Color selectedColor;

  ///显示列数
  final int crossAxisCount;

  ///item的高度是根据item的宽度的比例来计算的，当item宽度小的时候，要调高该值保证item的高度
  final double childAspectRatio;

  ///需要显示的数据
  final List<T>? items;

  /// 当为单选时点击时的回调，多选时不回调该tap
  final Function(T? data)? onTap;

  /// 当为多选时点击时的回调，单选时不回调该tap
  /// [sourceData] 源数据
  /// [selectData] 选择的数据
  final Function(List<T>? sourceData, List<T>? selectData)? onMultiTap;

  ///文本行数，默认一行
  final int maxLines;

  ///构建自定义widget
  final Function(T? data)? buildCustomChild;

  ///GridView的一些属性暴露
  final bool shrinkWrap;
  final ScrollPhysics? physics;
  final EdgeInsetsGeometry? padding;
  final double? mainAxisSpacing;
  final double? crossAxisSpacing;

  const KqCheckSelectableGridView({
    super.key,
    this.unselectedColor = KqThemeColors.bgBlack05,
    this.selectedColor = KqThemeColors.bgDefault,
    this.crossAxisCount = 3,
    this.items,
    this.onTap,
    this.childAspectRatio = 10,
    this.multiSelect = false,
    this.onMultiTap,
    this.shrinkWrap = true,
    this.physics = const NeverScrollableScrollPhysics(),
    this.padding = EdgeInsets.zero,
    this.mainAxisSpacing,
    this.crossAxisSpacing,
    this.maxLines = 1,
    this.buildCustomChild,
  });

  @override
  State<StatefulWidget> createState() => KqCheckSelectableGridViewState<T>();
}

class KqCheckSelectableGridViewState<T extends ICheckGridViewItemData>
    extends State<KqCheckSelectableGridView<T>> {
  @override
  Widget build(BuildContext context) {
    return GridView.count(
      ///Container跟随GridView内容变化高度, shrinkWrap:true;
      shrinkWrap: widget.shrinkWrap,

      ///取消滚动效果physics: NeverScrollableScrollPhysics();
      physics: widget.physics,
      padding: widget.padding,
      crossAxisCount: widget.crossAxisCount,
      childAspectRatio: widget.childAspectRatio,
      mainAxisSpacing: widget.mainAxisSpacing ?? 20.r,
      crossAxisSpacing: widget.crossAxisSpacing ?? 20.r,
      children: getItems(),
    );
  }

  List<Widget> getItems() {
    if (widget.items.isNullOrEmpty) {
      return [];
    }
    List<Widget> widgets = [];
    for (T data in widget.items!) {
      widgets.add(
        KqInkWell(
          backgroundColor: widget.unselectedColor,
          radius: 2.r,
          onTap: () {
            if (data.gridViewItemIsSelected) {
              if (widget.multiSelect) {
                data.gridViewItemIsSelected = false;
                widget.onMultiTap?.call(widget.items, getSelectedData());
                setState(() {});
              } else {
                data.gridViewItemIsSelected = false;
                widget.onTap?.call(null);
                setState(() {});
              }
            } else if (!data.gridViewItemIsSelected) {
              if (widget.multiSelect) {
                data.gridViewItemIsSelected = true;
                widget.onMultiTap?.call(widget.items, getSelectedData());
                setState(() {});
              } else {
                clearAllSelectedState();
                data.gridViewItemIsSelected = true;
                widget.onTap?.call(data);
                setState(() {});
              }
            }
          },
          child: Stack(
            children: [
              Container(
                width: double.infinity,
                height: double.infinity,
                alignment: Alignment.center,
                padding: EdgeInsets.only(left: 12.r, right: 12.r),
                decoration: BoxDecoration(
                  color: data.gridViewItemIsSelected
                      ? widget.selectedColor
                      : widget.unselectedColor,
                  borderRadius: BorderRadius.all(Radius.circular(2.r)),
                  border: Border.all(
                      width: 1.75.r,
                      color: data.gridViewItemIsSelected
                          ? KqThemeColors.bgBlue
                          : KqThemeColors.bgTransparent),
                ),
                child: widget.buildCustomChild?.call(data) ??
                    Text(
                      data.gridViewItemTitle,
                      maxLines: widget.maxLines,
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: data.gridViewItemIsSelected
                            ? KqThemeColors.textBlue
                            : KqThemeColors.text26,
                        fontSize: KqThemeManager.instance
                                .getConfig()
                                .formConfig
                                .contentFontSize ??
                            12.sp,
                        fontWeight: FontWeight.normal,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
              ),
              Positioned(
                right: 0,
                bottom: 0,
                child: Visibility(
                  visible: data.gridViewItemIsSelected,
                  child: KqImage.custom(
                    url: Images.commonIcXuanzhongBig,
                    package: KqGlobal.packageName,
                    imageType: ImageType.assets,
                    width: 40.r,
                    height: 35.r,
                  ),
                ),
              ),
            ],
          ),
        ),
      );
    }
    return widgets;
  }

  clearAllSelectedState() {
    for (T data in widget.items!) {
      data.gridViewItemIsSelected = false;
    }
  }

  List<T> getSelectedData() {
    List<T> selectedData = [];
    for (T data in widget.items!) {
      if (data.gridViewItemIsSelected) {
        selectedData.add(data);
      }
    }
    return selectedData;
  }
}

class ICheckGridViewItemData {
  ///显示文本
  @JsonKey(includeToJson: false, includeFromJson: false)
  String gridViewItemTitle;

  /// 是否选中
  @JsonKey(includeToJson: false, includeFromJson: false)
  bool gridViewItemIsSelected;

  ICheckGridViewItemData(
    this.gridViewItemTitle, {
    this.gridViewItemIsSelected = false,
  });
}
